# 工具链配置
CC = riscv64-unknown-elf-gcc
LD = riscv64-unknown-elf-ld
OBJCOPY = riscv64-unknown-elf-objcopy
OBJDUMP = riscv64-unknown-elf-objdump

# 编译选项
CFLAGS = -nostdlib -fno-builtin -mcmodel=medany -march=rv64gc -mabi=lp64
CFLAGS += -Iinclude -O2 -Wall -Wextra -Werror
CFLAGS += -ffreestanding -nostartfiles

# 链接选项
LDFLAGS = -T kernel/kernel.ld -nostdlib

# 源文件
SRC_DIR = kernel
ASM_SRCS = $(wildcard $(SRC_DIR)/*.S)
C_SRCS = $(wildcard $(SRC_DIR)/*.c)
OBJS = $(ASM_SRCS:.S=.o) $(C_SRCS:.c=.o)

# 默认目标
all: kernel.elf

# 编译规则
%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# 链接内核
kernel.elf: $(OBJS)
	$(LD) $(LDFLAGS) -o $@ $(OBJS)

# 生成二进制镜像
kernel.bin: kernel.elf
	$(OBJCOPY) -O binary $< $@

# 反汇编查看代码布局
disasm: kernel.elf
	$(OBJDUMP) -S $< > kernel.disasm

# 查看符号表
symbols: kernel.elf
	$(OBJDUMP) -t $<

# QEMU运行
qemu: kernel.elf
	qemu-system-riscv64 -machine virt -bios none -kernel $< -nographic

# QEMU调试模式
qemu-gdb: kernel.elf
	qemu-system-riscv64 -machine virt -bios none -kernel $< -nographic -s -S

# 清理
clean:
	rm -f kernel.elf kernel.bin $(OBJS) kernel.disasm

.PHONY: all clean qemu qemu-gdb disasm symbols
